package com.rhb.af.util;

import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;

import org.apache.commons.beanutils.BeanUtils;
import org.mvel2.MVEL;

public class Formula {
	public static boolean isFormula(String str){
		if(str!=null && (str.indexOf("+")!=-1 || str.indexOf("-")!=-1 ||str.indexOf("*")!=-1 || str.indexOf("/")!=-1)){
			return true;
		}else{
			return false;
		}
	}
	
	public static String getValue(Object obj,String formula) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException{
		if(obj!=null && formula!=null){
			Iterator iterat = BeanUtils.describe(obj).keySet().iterator();
			while (iterat.hasNext()) {
				String fn = (String)iterat.next();
				if (formula.indexOf(fn) != -1) {
					formula = formula.replaceAll(fn, BeanUtils.getProperty(obj, fn));
				}
			}
			
			String str = "";
			try{
				str = MVEL.eval(formula).toString();
			}catch(Exception e){}
			
			return str;
		}else{
			return formula;
		}
	}
}
